<template>
  <div>
    <!--        面包屑导航-->
    <breadcrumb :navData="navData"></breadcrumb>
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="active*1" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="add_form" label-width="80px" :rules="rules" ref="add_form">
        <!-- form表单包裹 -->
        <!-- 骨架屏 -->
        <el-tabs
          v-model="active"
          :tab-position="tabPosition"
          :before-leave="leaves_go"
          @tab-click="ontab_click"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 表单 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="add_form.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="add_form.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="add_form.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="add_form.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择 -->
              <el-cascader
                v-model="add_form.goods_cat"
                :options="options"
                :props="cas_pop"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyDynamic" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox
                  v-for="(it, index) in item.attr_values"
                  :key="index"
                  :label="it"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyDynamic" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="axios.defaults.baseURL+'upload'"
              :headers="headers"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="add_form.goods_introduce"></quill-editor>
            <!--                        添加商品按钮-->
            <el-button type="primary" class="add_btn" @click="onAddGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 下一步 -->
      <el-button style="margin-top: 12px;" @click="next">下一步</el-button>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "VueShopsAdd",

  data() {
    return {
      navData: ["商品管理", "商品列表"],
      active: 0,
      // 骨架屏位置
      tabPosition: "left",
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3s 到 15 个字符",
            trigger: "blur",
          },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
      add_form: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        goods_introduce: "",
        attrs: [],
        pics: [],
      },
      // 级联选择器配置
      options: [],
      cas_pop: {
        checkStrictly: true,
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 动态参数
      manyDynamic: [],
      // 静态参数
      onlyDynamic: [],
      //图片预览弹窗 图片地址
      dialogImageUrl: "",
      //图片预览弹窗隐藏显示
      dialogVisible: false,
      //上传图片请求头
      headers: {
        Authorization: window.sessionStorage.getItem("token"),
      },
    };
  },

  mounted() {},
  created() {
    this.getcas_list();
  },
  methods: {
    // 下一步
    next() {
      if (this.active++ > 5) this.active = 0;
    },
    // 基本信息分类数据
    async getcas_list() {
      const cas_data = await this.axios.get("/categories");
      console.log(cas_data);
      this.options = cas_data.data.data;
    },
    // 分类选择器三级分类判断
    handleChange() {
      if (this.add_form.goods_cat.length !== 3) {
        this.add_form.goods_cat = [];
        return this.$message.error("只能选择三级商品分类");
      }
    },
    // 向下切换tab判断
    leaves_go(activeName, oldActiveName) {
      console.log("当前" + activeName, "之前" + oldActiveName);
      if (oldActiveName === "0") {
        if (!this.add_form.goods_name) {
          // 无论做什么都会返回错误Promise.reject
          return Promise.reject(this.$message.error("请先输入商品名称"));
        }
        if (this.add_form.goods_cat.length !== 3) {
          return Promise.reject(this.$message.error("请先输入商品分类"));
        }
      }
    },

    // tab选项卡点击
    // attr_sel[only,many]不能为空
    ontab_click() {
      switch (this.active) {
        case "1": {
          this.getCommodity_parameters("many");
          break;
        }
        case "2": {
          this.getCommodity_parameters("only");
          break;
        }
      }
    },
    // 商品参数数据
    // this.cateId计算属性
    async getCommodity_parameters(sel) {
      if (this[sel + "Dynamic"].length !== 0) return;
      const data_params = await this.axios.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: sel,
          },
        }
      );
      console.log(data_params);
      if (data_params.data.meta.status == 200) {
        this.$message.success("获取成功");
      }
      if (sel === "many") {
        data_params.data.data.forEach((item) => {
          console.log(item);
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          item.attr_values = JSON.parse(JSON.stringify(item.attr_vals));
        });
      }
      this[sel + "Dynamic"] = data_params.data.data;
      console.log("获取分类参数数据====>", this[sel + "Dynamic"]);
    },
    // 商品图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 添加
    async onAddGoods() {
      console.log("点击添加商品按钮", this.add_form);
      // 深拷贝
      let addform = JSON.parse(JSON.stringify(this.add_form));
      addform.goods_cat = addform.goods_cat.join(",");
      //动态参数
      this.manyDynamic.forEach((item) => {
        addform.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(","),
        });
      });
      //静态属性
      this.onlyDynamic.forEach((item) => {
        addform.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals,
        });
      });
      console.log("点击添加商品按钮", addform);

      let goodslist = await this.axios.post("goods", addform);
      console.log("点击添加商品按钮", goodslist);
      if (goodslist.data.meta.status == 201) {
        this.$message.success("成功");
        this.$router.push("/goods");
      } else {
        this.$message.error("失败");
      }
    },
  },
  computed: {
    cateId() {
      if (this.add_form.goods_cat.length === 3) {
        return this.add_form.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-steps {
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>